package webappcontrollers



import (
"bytes"
"encoding/base64"
"smartcap-api/models"
"fmt"
"github.com/astaxie/beego/orm"
"github.com/dgrijalva/jwt-go"
"strings"
"time"
)

// 创建一个struct 用来生成token 具体的用法可以参照jwt-go
type Claims struct {
	Username string `json:"username"`
	Role string `json:"role"`
	Portraiturl string `json:"portraiturl"`
	jwt.StandardClaims
}

// 创建用户签名的JWT key
// 关于jwtKey的生成可以使用自己的算法来保证唯一性，这里为了简单就直接用字符串代替了
var jwtKey = []byte("beijingaskme201911061517")
// 创建token
func CreateToken(username string,role string, portraiturl string, expirationTime time.Time) (tokenString string, err error) {
	claims := Claims{
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
		},
	}
	claims.Username = username
	claims.Role = role
	claims.Portraiturl = portraiturl
	// 声明生成token的算法和claims
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 创建token字符串
	return token.SignedString(jwtKey)
}


//base64解码，用于解析token
func Decode(raw []byte) []byte {
	var buf bytes.Buffer
	decoded := make([]byte, 215)
	buf.Write(raw)
	decoder := base64.NewDecoder(base64.StdEncoding, &buf)
	decoder.Read(decoded)
	return decoded
}

//解析token
func ParseToken(token string)string  {
	tokensegment := strings.Split(token, ".")
	//fmt.Println(tokensegment)
	jsoninfo := Decode([]byte(tokensegment[1]))
	//fmt.Print(string(jsoninfo[:]))
	return string(jsoninfo[:])
}

//从jsoninfo中解析出用户名，暂用此方法
func Getusernamefromjsoninfo(jsoninfo string)  string  {
	bb := strings.Split(jsoninfo,",")
	//fmt.Println(bb[0])
	cc := strings.Split(bb[0],":")
	//fmt.Println(cc[1])
	dd := strings.Split(cc[1],"\"")
	//fmt.Println(dd[1])
	return dd[1]
}

//根据用户名查询用户所在公司
func QueryCompanyByUsername(username string)string {
	o := orm.NewOrm()
	var userrows []models.UserInfo
	if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ", username).QueryRows(&userrows); err != nil {
		fmt.Println("err")
	}
	company := ""
	for _, userrow := range userrows {
		company = userrow.Company
	}
	return company
}

//根据公司名返回公司id
func QueryCompanyidByCompany(company string) string {
	o := orm.NewOrm()
	var comprows []models.CompanyInfo
	if _, err := o.Raw("SELECT * FROM company_info WHERE companyname = ?  ", company).QueryRows(&comprows); err != nil {
		fmt.Println("err")
	}
	companyid := ""
	for _, comprow := range comprows {
		companyid = comprow.Companyid
	}
	return companyid
}



//从token中解析出公司名
func GetCompanyfromToken(token string) string {
	jsoninfo := ParseToken(token)
	username := Getusernamefromjsoninfo(jsoninfo)
	company := QueryCompanyByUsername(username)
	return company
}

//从json中解析信息
func Getinfofromjson(jsoninfo string) []string{
	bb := strings.Split(jsoninfo,",")
	labelinfoarray := []string{}
	for i := 0; i <len(bb); i ++ {
		cc := strings.Split(bb[i],":")
		labelinfoarray = append(labelinfoarray,strings.Split(cc[1],"\"")[1])
	}
	return labelinfoarray
}


//从数组中解析信息
func Getinfofromarray(arrayinfo string)[]string{
	//fmt.Println(arrayinfo)
	bb := strings.Split(arrayinfo,",")
	arrayinfoarray := []string{}
	for i := 0; i <len(bb); i ++ {
		cc := strings.Split(bb[i],"\"")
		arrayinfoarray = append(arrayinfoarray,cc[1])
	}
	return arrayinfoarray
}

